package org.springblade.modules.admin.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.admin.entity.UserSignDetail;
import org.springblade.modules.admin.service.MaintainSignSetingService;
import org.springblade.modules.admin.service.UserSignDetailService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户考勤数据初始化定时器
 *
 * @author zcc
 * @version 1.0
 * @date 2021/7/31 9:33
 */
@Component
@Slf4j
public class UserSignDetailInitJob {

	@Resource
	private UserSignDetailService userSignDetailService;

	@Resource
	private MaintainSignSetingService maintainSignSettingService;

	//@Scheduled(cron = "0 0 23 * * ?")
	@XxlJob(value = "userSignDetailInit")
	private void userSignDetailInit() {
		XxlJobHelper.handleSuccess("考勤定时器开始执行-(userSignDetailInit)-[执行]开始");
		log.info("考勤定时器开始执行.............执行时间=" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		final Integer tomorrow = Convert.toInt(DateUtil.format(DateUtil.tomorrow(), "yyyyMMdd"));
		log.info("考勤定时器执行参数............." + tomorrow);
		List<UserSignDetail> userSignDetailByDate = maintainSignSettingService.getUserSignDetailByDate(tomorrow);
		log.info("获取参与考勤的用户列表............" + userSignDetailByDate.size());
		List<UserSignDetail> saveList = new ArrayList<>(16);
		for (UserSignDetail userSignDetail : userSignDetailByDate) {
			if (userSignDetail.getHoliday() == 1) {
				userSignDetail.setSignBeLate(2);
				userSignDetail.setSignOutLeaveEarly(2);
			}
			saveList.add(userSignDetail);
		}
		try {
			userSignDetailService.saveBatch(saveList);
			XxlJobHelper.handleSuccess("考勤定时器开始执行-(userSignDetailInit)-[执行]成功");
		} catch (Exception e) {
			for (UserSignDetail userSignDetail : saveList) {
				try {
					userSignDetailService.save(userSignDetail);
				} catch (Exception e1) {
					log.info("添加用户考勤信息错误对象信息....." + JSON.toJSONString(userSignDetail));
					XxlJobHelper.handleSuccess("考勤定时器开始执行-(userSignDetailInit)-[执行]失败");
				}
			}

		}
		log.info("考勤定时器执行成功............");
	}
}
